<template>
  <div class="intelligence-center">
    <div class="sidebar">
      <el-input v-model="searchQuery" placeholder="搜索人员/公司" prefix-icon="Search" />
      <el-button type="primary" @click="buildProfile" :loading="loading" style="width: 100%; margin-top: 10px;">
        生成/刷新画像
      </el-button>
      
      <div class="entity-list">
        <div 
          v-for="entity in filteredEntities" 
          :key="entity.identifier" 
          class="entity-item"
          :class="{ active: selectedEntity && selectedEntity.identifier === entity.identifier }"
          @click="handleSelect(entity.identifier)"
        >
          <span class="entity-name">{{ entity.name }}</span>
          <el-tag size="small" :type="entity.entity_type === 'company' ? 'warning' : undefined">{{ entity.entity_type === 'company' ? '企' : '人' }}</el-tag>
        </div>
      </div>
    </div>

    <div class="main-content">
      <div class="graph-area">
        <RelationshipGraph :data="graphData" @node-click="handleSelect" />
      </div>
      <div class="details-area" v-if="selectedEntity">
        <div class="profile-header">
          <h3>{{ selectedEntity.name }}</h3>
          <el-tag size="small">{{ selectedEntity.entity_type === 'company' ? '企业' : '个人' }}</el-tag>
        </div>
        
        <el-descriptions :column="1" border size="small" class="profile-info">
          <el-descriptions-item label="身份证号" v-if="selectedEntity.id_card">{{ selectedEntity.id_card }}</el-descriptions-item>
          <el-descriptions-item label="性别" v-if="selectedEntity.gender">{{ selectedEntity.gender }}</el-descriptions-item>
          <el-descriptions-item label="出生日期" v-if="selectedEntity.birth_date">{{ selectedEntity.birth_date }}</el-descriptions-item>
          <el-descriptions-item label="籍贯/省份" v-if="selectedEntity.province">{{ selectedEntity.province }}</el-descriptions-item>
          <el-descriptions-item label="联系电话" v-if="selectedEntity.phones">
            <div v-for="phone in parseJson(selectedEntity.phones)" :key="phone">{{ phone }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="地址" v-if="selectedEntity.addresses">
             <div v-for="addr in parseJson(selectedEntity.addresses)" :key="addr">{{ addr }}</div>
          </el-descriptions-item>
          <el-descriptions-item label="银行账号" v-if="selectedEntity.accounts">
             <div v-for="acc in parseJson(selectedEntity.accounts)" :key="acc">{{ acc }}</div>
          </el-descriptions-item>
        </el-descriptions>

        <div v-if="selectedEntity.extra_data" class="extra-data">
          <el-divider content-position="left">扩展信息</el-divider>
          <el-descriptions :column="1" border size="small">
            <el-descriptions-item v-for="(val, key) in parseJson(selectedEntity.extra_data)" :key="key" :label="key">
              {{ val }}
            </el-descriptions-item>
          </el-descriptions>
        </div>

        <el-divider content-position="left">活动轨迹</el-divider>
        <TimelineView :activities="timelineData" />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue';
import { useRoute } from 'vue-router';
import { ElMessage, ElDescriptions, ElDescriptionsItem, ElTag, ElDivider, ElMenu, ElMenuItem } from 'element-plus';
import RelationshipGraph from '@/components/profile/RelationshipGraph.vue';
import TimelineView from '@/components/profile/TimelineView.vue';

const route = useRoute();
const caseId = computed(() => route.params.caseId || route.query.caseId || 1);

const entities = ref([]);
const searchQuery = ref('');
const loading = ref(false);
const graphData = ref({ nodes: [], edges: [] });
const selectedEntity = ref(null);
const timelineData = ref([]);

const filteredEntities = computed(() => {
  if (!searchQuery.value) return entities.value;
  return entities.value.filter(e => e.name.includes(searchQuery.value) || e.identifier.includes(searchQuery.value));
});

const loadData = async () => {
  try {
    console.log('[IntelligenceCenter] Loading profile data...');
    entities.value = await window.electronAPI.profile.getEntities(caseId.value);
    console.log('[IntelligenceCenter] Loaded entities:', entities.value);
    
    graphData.value = await window.electronAPI.profile.getGraph(caseId.value);
    console.log('[IntelligenceCenter] Loaded graph data:', graphData.value);
  } catch (error) {
    console.error('Failed to load profile data:', error);
  }
};

const buildProfile = async () => {
  loading.value = true;
  try {
    await window.electronAPI.profile.build(caseId.value);
    await loadData();
    ElMessage.success('画像生成完成');
  } catch (error) {
    ElMessage.error('画像生成失败');
  } finally {
    loading.value = false;
  }
};

const handleSelect = async (identifier) => {
  selectedEntity.value = entities.value.find(e => e.identifier === identifier);
  if (selectedEntity.value) {
    timelineData.value = await window.electronAPI.profile.getTimeline({
      caseId: caseId.value,
      identifier
    });
  }
};

const parseJson = (str) => {
  if (!str) return null;
  try {
    return typeof str === 'string' ? JSON.parse(str) : str;
  } catch (e) {
    return str;
  }
};

onMounted(() => {
  loadData();
});
</script>

<style scoped>
.intelligence-center {
  display: flex;
  height: 100vh;
}
.sidebar {
  width: 250px;
  border-right: 1px solid #eee;
  padding: 10px;
  display: flex;
  flex-direction: column;
}
.entity-list {
  flex: 1;
  overflow-y: auto;
  border-right: none;
}
.entity-item {
  padding: 12px 20px;
  cursor: pointer;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #f5f5f5;
  transition: background-color 0.2s;
}
.entity-item:hover {
  background-color: #f5f7fa;
}
.entity-item.active {
  background-color: #ecf5ff;
  color: #409eff;
  border-right: 2px solid #409eff;
}
.entity-name {
  font-size: 14px;
  font-weight: 500;
}
.main-content {
  flex: 1;
  display: flex;
}
.graph-area {
  flex: 2;
  border-right: 1px solid #eee;
}
.details-area {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: #fff;
  border-left: 1px solid #eee;
}
.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}
.profile-header h3 {
  margin: 0;
}
.profile-info {
  margin-bottom: 20px;
}
.extra-data {
  margin-top: 20px;
}
</style>
